<?php

namespace Xrfg\Api\Trading\Account\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;
use Xrfg\Core\Trading\Account\Models\Coin;
use Xrfg\Core\Trading\Account\Models\Transfer;
use Xrfg\Api\Trading\Account\Requests\TransferRequest;
use Xrfg\Api\Trading\Account\Resources\TransferResource;
use Xrfg\Core\Trading\Account\Models\Account as TradingAccount;

class TransferController extends Controller
{
    /**
     * 资金划转记录.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $coinName = $request->query('coin_name');
        $type = $request->query('type'); // account:币币账户 contract_account:合约账户
        $time = $request->query('time'); // 1-最近1个月 2-1到3个月
        $perPage = $request->query('per_page', 15);
        $perPage = $perPage > 100 ? 100 : $perPage;

        $transferLogs = Transfer::where('user_id', Auth::id())
            ->when(null !== $coinName, function ($query) use ($coinName) {
                $query->where('coin_id', Coin::where('name', $coinName)->value('id'));
            })
            ->when(in_array($type, ['account', 'spot_account']), function ($query) use ($type) {
                $query->where('from_account', $type);
            })
            ->when($time == 1, function ($query) { // 1-最近1个月
                return $query->where('time', '>=', now()->subMonths());
            })
            ->when($time == 2, function ($query) { // 2-1到3个月
                return $query->where('time', '>=', now()->subMonths(3))->where('time', '<', now()->subMonths(1));
            })
            ->orderByDesc('id')
            ->paginate($perPage);

        return TransferResource::collection($transferLogs);
    }

    /**
     * DSE收益币划转（收益币账户->交易账户）
     *
     * @param TransferRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function transfer(TransferRequest $request)
    {
        /** @var User $user */
        $user = Auth::user();
        $transfer_number = $request->input('transfer_number');
        $fee = bcmul($transfer_number, 0.1);

        // 出账账户
        $fromAccount = Account::firstOrCreate([
            'user_id' => $user->id,
            'coin_id' => 2,
        ])->refresh();
        if ($fromAccount->freeze < $transfer_number) {
            $this->error(20002);
        }

        // 入账账户
        $toAccount = TradingAccount::firstOrCreate([
            'user_id' => $user->id,
            'coin_id' => 2,
        ]);

        // 资金划转记录
        $transfer = new Transfer();
        $transfer->user_id = $user->id;
        $transfer->coin_id = 2;
        $transfer->number = $transfer_number;
        $transfer->fee = $fee;

        // 保存数据
        bcscale(8);
        try {
            DB::transaction(function () use ($fromAccount, $toAccount, $transfer) {
                /** @var Account $fromAccount */
                $fromAccount = Account::lockForUpdate()->find($fromAccount->id);
                /** @var TradingAccount $toAccount */
                $toAccount = TradingAccount::lockForUpdate()->find($toAccount->id);

                $transfer->save();

                $fromAccount->freezeDecrement($transfer->number);
                $fromAccount->type = '收益币转出';
                $fromAccount->action_id = $transfer->id;
                $fromAccount->save();

                $toAccount->availableIncrement(bcsub($transfer->number, $transfer->fee));
                $toAccount->proofId = [$transfer->id, Transfer::CLASS_ID, Transfer::OP_ACCOUNT_IN];
                $toAccount->save();
            });
        } catch (Throwable $exception) {
            Log::error($exception);
            $this->error();
        }

        return $this->null();
    }
}
